package com.vhall.component.service.interactive.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.vhall.component.dao.interactive.QuestionsMapper;
import com.vhall.component.dao.interactive.RoomQuestionLkMapper;
import com.vhall.component.entity.export.dto.AdminExportCommonQueryCondition;
import com.vhall.component.entity.interactive.entity.QuestionsEntity;
import com.vhall.component.entity.interactive.vo.QuestionAdmDeleteReqVO;
import com.vhall.component.entity.interactive.vo.QuestionAdmListReqVO;
import com.vhall.component.entity.interactive.vo.QuestionAdmRspVO;
import com.vhall.component.entity.page.vo.PageVO;
import com.vhall.component.entity.room.RoomQuestionLkEntity;
import com.vhall.component.framework.common.exception.BusinessException;
import com.vhall.component.framework.common.utils.StringUtils;
import com.vhall.component.plugin.common.exception.BizErrorCode;
import com.vhall.component.service.interactive.QuestionAdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Objects;
import java.util.Set;

/**
 * @author yuanzh
 * @date 2021/11/24
 */
@Slf4j
@Service
public class QuestionAdminServiceImpl implements QuestionAdminService {

    @Autowired
    private QuestionsMapper questionsMapper;

    @Autowired
    private RoomQuestionLkMapper roomQuestionLkMapper;

    private static final String QUESTIONS_CREATED_AT_COLUMN = "questions.created_at";

    @Override
    public PageVO<QuestionAdmRspVO> list(QuestionAdmListReqVO reqVO) {
        reqVO.setDefault();
        QueryWrapper<QuestionAdmRspVO> wrapper = new QueryWrapper<>();
        wrapper.ge(StringUtils.isNotEmpty(reqVO.getStartTime()), QUESTIONS_CREATED_AT_COLUMN,
                DateUtil.parseLocalDateTime(reqVO.getStartTime(), DatePattern.NORM_DATE_PATTERN));
        if (StringUtils.isNotEmpty(reqVO.getEndTime())) {
            wrapper.lt(QUESTIONS_CREATED_AT_COLUMN,
                    DateUtil.parseLocalDateTime(reqVO.getEndTime(), DatePattern.NORM_DATE_PATTERN).plusDays(1));
        }
        String keyword = reqVO.getKeyword();
        // 模糊查询支持，房间id、房间名称、创建人名称
        wrapper.and(StringUtils.isNotEmpty(keyword),
                w -> w.like("questions.title", keyword).or().like("account.nickname", keyword));
        wrapper.isNull("questions.deleted_at");
        wrapper.orderByDesc("questions.question_id");
        Page<QuestionAdmRspVO> page = new Page<>(reqVO.getPage(), reqVO.getPageSize());
        Page<QuestionAdmRspVO> pageResult = questionsMapper.listQuestionForAdmin(page, wrapper);
        return new PageVO<>(reqVO.getPage(), reqVO.getPageSize(), (int) page.getTotal(), pageResult.getRecords());
    }

    @Override
    public Set<String> delete(QuestionAdmDeleteReqVO reqVO) {
        Set<String> questionIds = reqVO.getQuestionIds();
        // 先根据问卷id查询是否有已发布的
        LambdaQueryWrapper<RoomQuestionLkEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.in(RoomQuestionLkEntity::getQuestionId, questionIds).eq(RoomQuestionLkEntity::getPublish, 1);
        if (roomQuestionLkMapper.selectCount(queryWrapper) > 0) {
            throw new BusinessException(BizErrorCode.COMP_QUESTION_NOT_DELETE);
        }
        LambdaUpdateWrapper<QuestionsEntity> updateWrapper = Wrappers.lambdaUpdate();
        LocalDateTime now = LocalDateTime.now();
        updateWrapper.in(QuestionsEntity::getQuestionId, questionIds).isNull(QuestionsEntity::getDeletedAt)
                .set(QuestionsEntity::getDeletedAt, now).set(QuestionsEntity::getUpdatedAt, now);
        int updCount = questionsMapper.update(null, updateWrapper);
        if (updCount <= 0) {
            log.error("删除问卷失败，questionIds：{}", questionIds);
            throw new BusinessException(BizErrorCode.BIZ_DELETE_FAILED);
        }
        return questionIds;
    }

    @Override
    public Integer countForAdminExport(AdminExportCommonQueryCondition condition) {
        QueryWrapper<Object> wrapper = new QueryWrapper<>();
        if (Objects.nonNull(condition)) {
            wrapper.ge(Objects.nonNull(condition.getStartTime()), QUESTIONS_CREATED_AT_COLUMN, condition.getStartTime());
            if (Objects.nonNull(condition.getEndTime())) {
                wrapper.lt(QUESTIONS_CREATED_AT_COLUMN, condition.getEndTime().plusDays(1));
            }
            String keyword = condition.getKeyword();
            // 模糊查询支持，房间id、房间名称、创建人名称
            wrapper.and(StringUtils.isNotEmpty(keyword),
                    w -> w.like("questions.title", keyword).or().like("account.nickname", keyword));
        }
        return questionsMapper.countQuestionForAdmin(wrapper);
    }
}
